package com.fenghongzhang.day008;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main3Activity extends AppCompatActivity {

    private Button writeBtn;
    private Button readBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        writeBtn = (Button) findViewById(R.id.write_btn);
        readBtn = (Button) findViewById(R.id.read_btn);

        writeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开一个文件输出流
                /**
                 * 1,文件名,存在就打开,不存在就创建
                 * 2,模式
                 */
                try {
                    FileOutputStream welcome = openFileOutput("welcome.txt", MODE_PRIVATE);
                    welcome.write("呵呵呵呵".getBytes());
                    welcome.flush();
                    welcome.close();

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        readBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //读
                try {
                    FileInputStream fileInputStream = openFileInput("welcome.txt");

                    //
                    StringBuffer stringBuffer = new StringBuffer();

                    byte[] b = new byte[1024];
                    int len = 0;
                    while((len = fileInputStream.read(b)) != -1){
                        String s = new String(b, 0, len);
                        stringBuffer.append(s);
                    }

                    String s = stringBuffer.toString();
                    Toast.makeText(Main3Activity.this, s, Toast.LENGTH_SHORT).show();


                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
